package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"time"
	"tools"
)

type Scene struct {
	Id             string `orm:"column(id);pk" json:"id" form:"id"`
	UserId         string `orm:"column(user_id)" json:"user_id" form:"user_id"`
	Name           string `orm:"column(name)" json:"name" form:"name"`
	CreateTime     int64  `orm:"column(create_time)" json:"create_time" form:"create_time"`
	EquipmentCount int    `orm:"-" json:"equipment_count"`
}

func init() {
	orm.RegisterModel(new(Scene))
}

func (m *Scene) TableName() string {
	return "scene"
}

func NewScene() *Scene {
	return &Scene{}
}

func GetSceneById(id string) (*Scene, error) {
	scene := &Scene{Id: id}
	err := orm.NewOrm().Read(scene)
	if err == orm.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		logs.Warn("GetSceneById error:", err)
		return nil, err
	}
	scene.EquipmentCount, _ = GetEquipmentCountByUid(scene.UserId, map[string]interface{}{
		"scene_id": id,
	})
	return scene, nil
}

func GetAllSceneByUid(uid string, page int) ([]*Scene, error) {
	var (
		lists []*Scene
		qs    orm.QuerySeter
		err   error
	)

	qs = orm.NewOrm().QueryTable(NewScene().TableName()).Filter("user_id", uid).OrderBy("-create_time")

	if page > 0 {
		row := beego.AppConfig.DefaultInt("page_limit", 20)
		start := (page - 1) * row
		qs = qs.Limit(row).Offset(start)
	}

	if _, err = qs.All(&lists); err != nil {
		logs.Error("GetAllSceneByUid error:", err)
		return nil, err
	}

	if len(lists) == 0 {
		return nil, nil
	}

	for k, v := range lists {
		lists[k].EquipmentCount, _ = GetEquipmentCountByUid(v.UserId, map[string]interface{}{"scene_id": v.Id})
	}

	return lists, nil
}

func AddScene(uid, name string) error {
	scene := &Scene{
		Id:         tools.GUUID(),
		CreateTime: time.Now().Unix(),
		UserId:     uid,
		Name:       name,
	}
	if _, err := orm.NewOrm().Insert(scene); err != nil {
		logs.Error("AddScene error:", err)
		return err
	}
	return nil
}

// 是否存在该场景名称
func IsExistsSceneByName(uid, name string, sid ...string) (bool, error) {
	vals := []interface{}{uid, name}
	sql := `SELECT count(id) FROM scene WHERE user_id = ? AND name = ?`
	if len(sid) > 0 {
		sql += " and id != ?"
		vals = append(vals, sid[0])
	}

	var count int
	if err := orm.NewOrm().Raw(sql).SetArgs(vals).QueryRow(&count); err != nil {
		logs.Error("IsExistsSceneByName error:", err)
		return false, err
	}
	if count == 0 {
		return false,nil
	}

	return true, nil
}

func UpdateScene(s *Scene) bool {
	c, err := orm.NewOrm().Update(s)
	if err != nil {
		logs.Error("UpdateScene error:", err)
		return false
	}
	if c == 0 {
		return false
	}
	return true
}

func DelSceneById(id string) bool {
	c, err := orm.NewOrm().Delete(&Scene{Id:id})
	if  err != nil {
		logs.Error("DelSceneById error:", err)
		return false
	}
	if c == 0 {
		return false
	}
	return true

}
